package com.fuelstations.coderone;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.example.androidhive.R;
import com.google.android.gms.common.GooglePlayServicesUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;

import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class FuelStationMain extends Activity {

	// private static int id;
	private static String company;
	private static String owner;
	private static String city;
	private static String address;
	private static String district;
	private static int postalcode;
	private static float unld95;
	private static float unld98;
	private static float unld100;
	private static float diesel;
	private static float dieselheat;
	private static float kerosene;

	// English Data
	private static String owner_en;
	private static String city_en;
	private static String address_en;
	private static String district_en;
	//
	private static double lat = 0.0;
	private static double lng = 0.0;
	//


	public static DatabaseHelper databaseHelper;

	// TODO remove later
	private static boolean f = true;

	//
	private static int pos_city = 0;
	private static int pos_district = 0;
	private static int pos_fuelType = 0;
	private static String pos_strCity=null;
	private static String pos_strDistrict=null;
	private static String pos_strFuelType=null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final ArrayList<HashMap<String, String>> stationsList = new ArrayList<HashMap<String, String>>();
		databaseHelper = DatabaseHelper.getDatabaseHelper(this.getApplicationContext());
		Images.setContext(getApplicationContext());

		Strings.setContext(getApplicationContext());

		if (!f) {

			NodeList nl = null;

			databaseHelper.deleteAllStations();

			try {
				URL url = new URL("http://192.168.1.101/~tdemetriou/b.xml");
				//URL url = new URL("http://macbook-pro.lan/~theodorosdemetriou/b.xml");
				// URL url = new
				// URL("http://maps.googleapis.com/maps/api/geocode/xml?address=%CE%93%CF%89%CE%BD%CE%AF%CE%B1+%CE%9D%CE%B1%CF%85%CE%B1%CF%81%CE%AF%CE%BD%CE%BF%CF%85+2+%26+%CE%A4%CE%B1%CE%B3%CE%BC%CE%B1%CF%84%CE%AC%CF%81%CF%87%CE%BF%CF%85+%CE%A0%CE%BF%CF%85%CE%BB%CE%AF%CE%BF%CF%85+%CE%9B%CE%B5%CF%85%CE%BA%CF%89%CF%83%CE%AF%CE%B1+%CE%9B%CE%95%CE%A5%CE%9A%CE%A9%CE%A3%CE%99%CE%91&sensor=false");

				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				InputSource is = new InputSource(url.openStream());
				is.setEncoding("UTF-8");
				Document doc = db.parse(is);
				doc.getDocumentElement().normalize();

				nl = doc.getElementsByTagName(HashTags.KEY_STATION);
				// looping through all song nodes <song>

			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}

			for (int i = 0; i < nl.getLength(); i++) {
				int inc = 1;

				Element e = (Element) nl.item(i);
				NodeList a = e.getChildNodes();
				Element b = (Element) a.item(inc);
				NodeList c = b.getChildNodes();
				String s = c.item(0).getNodeValue();

				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				company = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				owner = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				city = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				address = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				district = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				postalcode = Integer.parseInt(s);
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				unld95 = Float.parseFloat(s);
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				unld98 = Float.parseFloat(s);
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				unld100 = Float.parseFloat(s);
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				diesel = Float.parseFloat(s);
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				dieselheat = Float.parseFloat(s);
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				kerosene = Float.parseFloat(s);
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				owner_en = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				city_en = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				address_en = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				s = c.item(0).getNodeValue();
				district_en = s;
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				if (c.item(0) != null) {
					s = c.item(0).getNodeValue();
					lat = Double.parseDouble(s);
				}
				//
				inc += 2;
				b = (Element) a.item(inc);
				c = b.getChildNodes();
				if (c.item(0) != null) {
					s = c.item(0).getNodeValue();
					lng = Double.parseDouble(s);
				}
				//

				databaseHelper.insertStation(company, owner, city, address, district, postalcode, unld95, unld98, unld100, diesel, dieselheat, kerosene, owner_en, city_en, address_en, district_en,
						lat, lng);

			}
			f = true;
		}
		// Main Screen Text
		final TextView txtCity = (TextView) findViewById(R.id.txtCity);
		final TextView txtDistrict = (TextView) findViewById(R.id.txtDistrict);
		final TextView txtFuelType = (TextView) findViewById(R.id.txtFuelType);
		

		//
		final Dialog dialog = new Dialog(FuelStationMain.this);
		final ListView list;
		final StationAdapter adapter;
		
		list = (ListView) findViewById(R.id.list);

		//stationsList = databaseHelper.getAllStations(pos_strCity, pos_strDistrict, pos_strFuelType);
		adapter = new StationAdapter(this, stationsList);
		list.setAdapter(adapter);

		// Click event for single list row
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ArrayList<HashMap<String, String>> st = new ArrayList<HashMap<String, String>>();
				
				st = databaseHelper.getAllStations(pos_strCity, pos_strDistrict, pos_strFuelType);
				
				Intent intent = new Intent(getApplicationContext(), Maps.class);
				String lat = st.get(position).get(HashTags.KEY_LAT);
				String lng = st.get(position).get(HashTags.KEY_LNG);
				String addr = st.get(position).get(HashTags.KEY_ADDRESS);

				intent.putExtra("lat", lat);
				intent.putExtra("lng", lng);
				intent.putExtra("addr", addr);
				startActivity(intent);
			}
		});


		ImageButton button1main = (ImageButton) findViewById(R.id.Button01main);

		button1main.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// set up dialog

				
				dialog.setContentView(R.layout.dialog);

				dialog.setTitle("This is my custom dialog box");
				dialog.setCancelable(true);
				final Spinner spnCity = (Spinner) dialog.findViewById(R.id.spnCity);
				final Spinner spnDistrict = (Spinner) dialog.findViewById(R.id.spnDistrict);
				final Spinner spnFuelType = (Spinner) dialog.findViewById(R.id.spnFuelType);
				final TextView text = (TextView) dialog.findViewById(R.id.TextView01);

				/*---spnCity---*/

				ArrayList<String> cl = new ArrayList<String>();
				cl = databaseHelper.getAllCities();
				String[] citiesArr = new String[cl.size()];
				citiesArr = cl.toArray(citiesArr);
				ArrayAdapter adapterCity = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, citiesArr);
				spnCity.setAdapter(adapterCity);
				spnCity.setSelection(pos_city, false);
				spnCity.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						pos_city = arg2;

						ArrayList<String> dl = new ArrayList<String>();
						dl = databaseHelper.getDistrictOfCities(spnCity.getSelectedItem().toString());

						String[] districtsArr = new String[dl.size()];
						districtsArr = dl.toArray(districtsArr);

						ArrayAdapter adapterDistrict = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, districtsArr);
						spnDistrict.setAdapter(adapterDistrict);

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						ArrayList<String> dl = new ArrayList<String>();
						dl = databaseHelper.getDistrictOfCities(spnCity.getItemAtPosition(pos_city).toString());

						String[] districtsArr = new String[dl.size()];
						districtsArr = dl.toArray(districtsArr);

						ArrayAdapter adapterDistrict = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, districtsArr);
						spnDistrict.setAdapter(adapterDistrict);

					}
				});

				/*-end--spnCity---*/

				/*---spnDistrict---*/

				ArrayList<String> dl = new ArrayList<String>();
				dl = databaseHelper.getDistrictOfCities(spnCity.getSelectedItem().toString());
				String[] districtsArr = new String[dl.size()];
				districtsArr = dl.toArray(districtsArr);
				ArrayAdapter adapterDistrict = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, districtsArr);
				spnDistrict.setAdapter(adapterDistrict);
				spnDistrict.setSelection(pos_district, false);

				spnDistrict.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						pos_district = arg2;

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});
				/*-end--spnDistrict---*/

				/*---spnFuelType---*/

				String[] fuelTypessArr = new String[Strings.getFuelTypes().size()];
				fuelTypessArr = Strings.getFuelTypes().toArray(fuelTypessArr);
				ArrayAdapter adapterFuelType = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, fuelTypessArr);
				spnFuelType.setAdapter(adapterFuelType);
				spnFuelType.setSelection(pos_fuelType, false);

				spnFuelType.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						pos_fuelType = arg2;

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});

				/*-end--spnFuelType---*/

				// set up button
				Button button = (Button) dialog.findViewById(R.id.Button01);
				button.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// s = text.getText().toString();
						pos_strCity = spnCity.getSelectedItem().toString();
						pos_strDistrict = spnDistrict.getSelectedItem().toString();
						if (pos_strDistrict.equals(Strings.districtAll.replaceAll("\'", "")))
							pos_strDistrict = null;
						pos_strFuelType = Strings.getColumnNameFromFuelType(spnFuelType.getSelectedItem().toString());

						final ArrayList<HashMap<String, String>> sl = databaseHelper.getAllStations(pos_strCity, pos_strDistrict, pos_strFuelType);

						list.setAdapter(new StationAdapter(FuelStationMain.this, sl));

						//
						if (pos_strCity == null) pos_strCity = Strings.citiesAll.replaceAll("'", "");
						if (pos_strDistrict == null) pos_strCity = Strings.districtAll.replaceAll("'", "");
						if (pos_strFuelType == null) pos_strFuelType = Strings.unld95;
						//
						txtCity.setText(pos_strCity);
						txtDistrict.setText(pos_strDistrict);
						txtFuelType.setText(Strings.getFuelTypeFromColumnName(pos_strFuelType));
						//
						
						dialog.dismiss();
					}
				});
				// now that the dialog is set up, it's time to show it
				dialog.show();
			}
		});

		// /
	}

	@Override
	protected void onResume() {
		super.onResume();
		// if(GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext())
		// == SUCCESS

	}
}